<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="small">
      <!-- 基本信息 -->
      <div class="form-section">
        <h3>基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产编号" prop="assetNo">
              <el-input v-model="form.assetNo" placeholder="请输入资产编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备号" prop="deviceNo">
              <el-input v-model="form.deviceNo" placeholder="请输入设备号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称" prop="assetName">
              <el-input v-model="form.assetName" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入位置" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格型号" prop="modelNo">
              <el-input v-model="form.modelNo" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="equipmentTypeCode">
              <el-select v-model="form.equipmentTypeCode" placeholder="请选择设备类型" style="width: 100%">
                <el-option
                  v-for="type in equipmentTypeOptions"
                  :key="type.dictValue"
                  :label="type.dictLabel"
                  :value="type.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入制造商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入供应商" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="使用部门" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入使用部门" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作人员" prop="operatorName">
              <el-input v-model="form.operatorName" placeholder="操作人员" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购入日期" prop="purchaseDate">
              <el-date-picker
                v-model="form.purchaseDate"
                type="datetime"
                placeholder="请选择购入日期"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="handlePurchaseDateChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="投产日期" prop="commissioningDate">
              <el-date-picker
                v-model="form.commissioningDate"
                type="datetime"
                placeholder="请选择投产日期"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="handleCommissioningDateChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 模具图片 -->
      <div class="form-section" style="margin-top: 30px;">
        <h3>模具图片</h3>
        <div class="upload-tip">最多上传5张，单张不大于2MB</div>
        <div class="upload-container">
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :limit="5"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-exceed="handleExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" size="tiny">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </div>
      </div>

      <div style="text-align: right; margin-top: 30px;">
        <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { getAsset, addAsset, updateAsset } from "@/api/asset/asset";
import { getDicts } from "@/api/dict/data";
import { getToken } from "@/utils/auth";
import request from "@/utils/request";

export default {
  name: "AssetForm",
  data() {
    return {
      // 表单参数
      form: {
        assetNo: null,
        assetName: null,
        deviceNo: null,
        location: null,
        modelNo: null,
        equipmentTypeCode: null,
        brand: null,
        manufacturer: null,
        supplierName: null,
        deptName: null,
        operatorName: null,
        purchaseDate: null,
        commissioningDate: null,
        statusCode: "ASSET_STATUS_001",
        imageUrls: []
      },
      // 原始表单数据快照
      originalForm: null,
      // 表单校验
      rules: {
        assetNo: [
          { required: true, message: "资产编号不能为空", trigger: "blur" }
        ],
        deviceNo: [
          { required: true, message: "设备号不能为空", trigger: "blur" }
        ],
        assetName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        location: [
          { required: true, message: "位置不能为空", trigger: "blur" }
        ],
        modelNo: [
          { required: true, message: "规格型号不能为空", trigger: "blur" }
        ],
        equipmentTypeCode: [
          { required: true, message: "设备类型不能为空", trigger: "change" }
        ],
        brand: [
          { required: true, message: "品牌不能为空", trigger: "blur" }
        ],
        manufacturer: [
          { required: true, message: "制造商不能为空", trigger: "blur" }
        ],
        supplierName: [
          { required: true, message: "供应商不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "使用部门不能为空", trigger: "blur" }
        ],
        operatorName: [
          { required: true, message: "操作人员不能为空", trigger: "blur" }
        ],
        purchaseDate: [
          { required: true, message: "购入日期不能为空", trigger: "change" }
        ],
        commissioningDate: [
          { required: true, message: "投产日期不能为空", trigger: "change" },
          { validator: this.validateCommissioningDate, trigger: "change" }
        ]
      },
      // 是否编辑模式
      isEdit: false,
      // 加载状态
      loading: false,
      // 设备类型选项
      equipmentTypeOptions: [],
      // 文件列表
      fileList: [],
      // 上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 上传请求头
      uploadHeaders: {
        Authorization: "Bearer " + getToken()
      },
      // 图片预览
      dialogVisible: false,
      dialogImageUrl: ''
    };
  },
  created() {
    this.getEquipmentTypeOptions();
    
    // 自动填充当前登录用户名
    this.form.operatorName = this.getCurrentUserName();
    
    // 保存初始表单状态
    this.originalForm = { ...this.form };
    
    // 判断是编辑还是新增
    const assetNo = this.$route.params.assetNo;
    if (assetNo) {
      this.isEdit = true;
      this.getAsset(assetNo);
    }
  },
  methods: {
    /** 获取当前登录用户名 */
    getCurrentUserName() {
      try {
        const store = this.$store;
        return (store && store.getters && store.getters.name) || '';
      } catch(e) {
        return '';
      }
    },
    /** 获取资产详情 */
    getAsset(assetNo) {
      getAsset(assetNo).then(response => {
        this.form = response.data;
        // 保存原始数据快照
        this.originalForm = { ...response.data };
        // 处理图片列表
        if (this.form.imageUrls && this.form.imageUrls.length > 0) {
          this.fileList = this.form.imageUrls.map((url, index) => ({
            name: `image_${index + 1}.jpg`,
            url: url
          }));
        }
      });
    },
    /** 监听购入日期变化，触发投产日期验证 */
    handlePurchaseDateChange() {
      // 如果已经填写了投产日期，则触发验证
      if (this.form.commissioningDate) {
        this.$refs.form.validateField('commissioningDate');
      }
    },
    /** 监听投产日期变化，触发投产日期验证 */
    handleCommissioningDateChange() {
      // 当投产日期变化时，触发验证
      if (this.form.commissioningDate) {
        this.$refs.form.validateField('commissioningDate');
      }
    },
    /** 获取设备类型选项 */
    getEquipmentTypeOptions() {
      request({ url: '/system/type/list', method: 'get', params: { pageNum: 1, pageSize: 9999, enabled: 1 } }).then(response => {
        this.equipmentTypeOptions = (response.rows || []).map(item => ({
          dictValue: item.code,
          dictLabel: item.name
        }));
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true;
          // 处理图片URLs
          this.form.imageUrls = this.fileList.map(file => file.url || file.response.url);
          
          if (this.isEdit) {
            updateAsset(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.loading = false;
              this.$router.push({ path: "/system/asset" });
            }).catch(() => {
              this.loading = false;
            });
          } else {
            addAsset(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.loading = false;
              this.$router.push({ path: "/system/asset" });
            }).catch(() => {
              this.loading = false;
            });
          }
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      // 检查表单是否有更改
      if (this.originalForm) {
        // 创建当前表单数据副本用于比较（排除图片列表）
        const currentForm = { ...this.form };
        const originalForm = { ...this.originalForm };
        
        // 删除不需要比较的字段
        delete currentForm.imageUrls;
        delete originalForm.imageUrls;
        
        // 比较数据是否有变更
        const hasChanged = JSON.stringify(currentForm) !== JSON.stringify(originalForm);
        if (hasChanged) {
          this.$modal.confirm('内容没有保存，是否取消？').then(() => {
            this.$router.push({ path: "/system/asset" });
          }).catch(() => {
            // 用户点击取消，不执行任何操作
          });
        } else {
          this.$router.push({ path: "/system/asset" });
        }
      } else {
        // 没有原始数据快照直接返回
        this.$router.push({ path: "/system/asset" });
      }
    },
    /** 上传成功回调 */
    handleUploadSuccess(response, file, fileList) {
      this.fileList = fileList;
    },
    /** 删除文件回调 */
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    /** 上传前校验 */
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    /** 图片预览 */
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /** 文件数量超出限制 */
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传 5 张图片，当前选择了 ${files.length} 张图片，共选择了 ${files.length + fileList.length} 张图片`);
    },
    /** 验证投产日期必须在购入日期之后 */
    validateCommissioningDate(rule, value, callback) {
      if (value && this.form.purchaseDate) {
        const purchaseDate = new Date(this.form.purchaseDate);
        const commissioningDate = new Date(value);
        if (commissioningDate.getTime() < purchaseDate.getTime()) {
          callback(new Error("投产日期必须在购入日期之后"));
          return;
        }
      }
      callback();
    }
  }
};
</script>

<style scoped>
.form-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.form-section h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 10px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-bottom: 10px;
}

.upload-container {
  margin-top: 10px;
}

/* 上传组件样式调整 */
.upload-container .el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;
}

.upload-container .el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
}
</style>